import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import { setlsItem, getlsItem, clearls } from '@/utils/lstorage'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'
import Nprogress from "nprogress"
import 'nprogress/nprogress.css'
axios.defaults.withCredentials = true //让ajax携带cookie
    // 创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
    timeout: 60000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    }
})

// request拦截器
service.interceptors.request.use(

    config => {
        //     if (getToken() != null) {
        //         config.headers['Authorization'] = `Bearer ${getToken()}` // 让每个请求携带自定义token 请根据实际情况自行修改
        //     }

        // Nprogress.start()
        return config
    },
    error => {
        // Do something with request error
        Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(

    response => {
        const { data, status } = response
        if (status === 200) {
            if (data.code == '200') {
                return data
            } else if (data.code === 'failed') {
                Message.error('系统内部错误!');
                return
            } else if (data.code === '001') {
                Message.error('未知错误!');
                return
            } else if (data.code === '002') {
                Message.error('主键冲突!');
                return
            } else if (data.code === '003') {
                Message.error('账号不存在!');
                return
            } else if (data.code === '004') {
                Message.error('账户名或密码错误!');
                return
            } else if (data.code === '005') {
                Message.error('账户锁定!');
                return
            } else if (data.code === '006') {
                Message.error('未认证!');
                return
            } else if (data.code === '007') {
                clearls()
                Message.error('被踢出！')
                router.push(`/login`)
                return
            } else if (data.code === '008') {
                clearls()
                Message.error('用户登录过期，请重新登录')
                router.push(`/login`)
                return
            } else if (data.code === '旧密码错误') {
                return data
            } else if (typeof data === 'string') {
                return response
            } else if (data.code) {
                return data
            } else {
                return data
            }
        } else {
            Message.error('请求错误!');
        }

    },
    error => {
        console.log(error.request)
        if (error.request.status === 401) {
            Message('用户登录过期，请重新登录')
            removeToken()
            clearls()
            router.push(`/login`)
        } else {
            Message.error("连接失败")
        }
        return Promise.reject(error)
    },
)

export default service